const express = require("express");
const apiRouter = express.Router();
const writeData = require("../../../db/module/writeData");
const readData = require("../../../db/module/readData");
const delData = require("../../../db/module/delData");

apiRouter.post("/bookList", async (req, res) => {
  // 获取到客户端通过查询字符串发送到服务器的数据
  try {
    const params = req.body;

    let result = await readData(params, "bookList");
    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

apiRouter.post("/getCarList", async (req, res) => {
  try {
    const params = req.body;

    let result = await readData(params, "bookCar");
    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

apiRouter.post("/addBookInfo", async (req, res) => {
  try {
    const params = req.body;
    let createTime = params.createTime
      ? params.createTime
      : new Date().toLocaleString();

    params.createTime = createTime;

    let userJurisdiction = [
      { name: "悬疑", value: "1" },
      { name: "惊悚", value: "2" },
      { name: "言情", value: "3" },
      { name: "犯罪", value: "4" },
      { name: "爽文", value: "5" },
    ];

    params.bookTypeName = userJurisdiction.filter(
      (item) => item.value == params.bookType
    )[0].name;

    let result = await writeData(params, "bookList");

    res.send(result);
  } catch (error) {

    res.send({
      code: 50000,
      msg: error,
    });
  }
});

apiRouter.post("/addCart", async (req, res) => {
  try {
    let params = req.body;
    let result = await writeData(params, "bookCar");
    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error.message,
    });
  }
});
apiRouter.post("/deleteboot", async (req, res) => {
  try {
    const params = req.body;

    let result = await delData(params, "bookList");

    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error.message,
    });
  }
});

apiRouter.post("/deletebootCar", async (req, res) => {
  try {
    const params = req.body;

    let result = await delData(params, "bookCar");

    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error.message,
    });
  }
});

module.exports = apiRouter;
